package com.yc.controller;

import com.yc.common.utils.AllConstans;
import com.yc.common.utils.JsonUtils;
import com.yc.common.utils.QRCodeUtil;
import com.yc.service.StudentInfoService;
import com.yc.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.OutputStream;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2023/8/1 13:32
 */
@Api("二维码控制器")
@RestController
@RequestMapping("/qrcode")
public class QrCodeController {

    @Resource
    private RedisTemplate redisTemplate;
    private static final String DISK_PATH = AllConstans.STU_UPLOAD_PATH + "qrcode/";
    // 存放时间的集合 键为uuid
    public static Map<String, String> SAVE_TIMESTAMP = new HashMap<>();


    @Resource
    StudentInfoService studentInfoService;

    // 生成二维码时调用
    @ApiOperation("生成二维码")
    @GetMapping("/create/{uuid}/{classroom}")
    public Result qrcode(@ApiParam(name = "uuid", value = "二维码的唯一标识", required = true)
                         @PathVariable("uuid") String uuid,
                         @ApiParam(name = "classroom", value = "上课教室", required = true)
                         @PathVariable("classroom") String classroom,
                         String url, OutputStream outputStream, HttpServletRequest request) throws Exception {
        // 在网页中生成二维码
        long timeMillis = System.currentTimeMillis();
        String path = DISK_PATH + uuid + "/" + timeMillis + ".jpg";
        path = path.replace("file:", "");
        String firstTimestamp = SAVE_TIMESTAMP.get(uuid);
        // 判断是否生成过二维码 没有就将路径存放到SAVE_TIMESTAMP集合中
        if (firstTimestamp == null || firstTimestamp.length() <= 0){
            firstTimestamp = timeMillis + "";
            SAVE_TIMESTAMP.put(uuid, firstTimestamp);
        }
        String webUrl = request.getRequestURL().toString();
        String prefix =webUrl.substring(webUrl.indexOf("/jkykq"), webUrl.indexOf("/qrcode"));
        InetAddress inetAddress = InetAddress.getLocalHost();
        // 二维码中的路径
        url = "http://" + inetAddress.getHostAddress() + prefix + "/qrcode/get/info/" + uuid + "/" + firstTimestamp + "/" + timeMillis + "/" + classroom;
        // 将二维码保存到磁盘中
        QRCodeUtil.encode(url, null, path, false);
        Result<String> result = new Result<>("../uploadfile/" + "qrcode/" + uuid + "/" + timeMillis + ".jpg");
        return result;
    }

    @ApiOperation("根据班级Id查询出学生存入redis")
    @PostMapping("/get/students/{uuid}")
    public Result selectStudentsByCid(@ApiParam(name = "uuid", value = "唯一标识", required = true)
                                    @PathVariable("uuid") String uuid,
                                    @RequestBody List<String> cids) {
        Object result = studentInfoService.selectStudentsByCid(uuid, cids);
        return Result.success(result);
    }


    // 扫描二维码时调用
    @ApiOperation("获取扫码人信息")
    @GetMapping("/get/info/{uuid}/{timeout}/{timing}/{stuid}/{stuname}/{cid}")
    public Result getInfo(@ApiParam(name = "uuid", value = "二维码的唯一标识", required = true)
                          @PathVariable("uuid") String uuid,
                          @PathVariable("timeout") Long timeout,
                          @ApiParam(name = "stuid", value = "扫码学生的学号", required = true)
                          @PathVariable("stuid") String stuid,
                          @ApiParam(name = "stuname", value = "扫码学生的姓名", required = true)
                          @PathVariable("stuname") String stuname,
                          @ApiParam(name = "cid", value = "班级编号", required = true)
                          @PathVariable("cid") String cid,
                          @RequestParam(value = "picUrl", required = false) String picUrl) {

        //成功之后就开始改变查询出来的状态
        QrCodeEndpoint qrCodeEndpoint = QrCodeEndpoint.onlineQrCode.get(uuid);
        if (qrCodeEndpoint == null){
            return Result.error("考勤完毕，修改请找上课老师!");
        }

        //改变缓存当中的状态
        Map<String, String> data = (Map<String, String>) redisTemplate.opsForValue().get(uuid);
        assert data != null;
        String key = cid + "-" + stuid + "-" + stuname;
        if (data.containsKey(key)){
            String value = data.get(key);
            if ("1".equals(value.substring(0, 1))){
                return Result.success("请勿重复签到!");
            }
            data.put(key, "1" + data.get(key).substring(1));
            redisTemplate.opsForValue().set(uuid, data);
            //改变页面的状态的前提条件
            Map<String, String> messaage = new ConcurrentHashMap<>();
            messaage.put("cid", cid);
            messaage.put("stuid", stuid);
            messaage.put("sname", stuname);
            messaage.put("status", "已到");
            // 拍照学生 将拍照的图片发送给前端
            if (picUrl != null && picUrl.indexOf("[") > -1){
                picUrl = picUrl.replaceAll("[\"]*[\\[]?[\\]]?", "");
                picUrl = picUrl.replace("\\\\", "/");
                picUrl = "../uploadfile/" + picUrl;
                messaage.put("image", picUrl);
            }
            String str = JsonUtils.objectToJson(messaage);
            qrCodeEndpoint.onMessage(uuid, str);
            return Result.success("签到成功!");
        }else {
            return Result.error("签到失败,没有该用户!");
        }
        //再修改
    }
}
